import { useEffect, useRef } from 'react';
import styles from './index.module.less';
import { Vector3 } from 'three';
import { OrbitControls } from './../../utils/OrbitControls';

import * as THREE from 'three';

let camera: any;
let _mesh: any;
let _canvas: any;
let _scene:any;
let _furniture: any;
let _materialMap: any = {};

const initControls = (camera: THREE.PerspectiveCamera, domElement: Document | HTMLCanvasElement | undefined) => {
  const controls = new OrbitControls(camera, domElement);
  // controls.target.set(camera.position.x, camera.position.y, camera.position.z); 
  controls.target.set(0, 0, 0);
  // 缩放限制
  controls.maxDistance = 100000;
  controls.minDistance = 1;
  // 垂直旋转限制
  controls.minPolarAngle = Math.PI / 2;
  controls.minPolarAngle = Math.PI / 2;
}

const renderFurniture = (childData: any) => {
  const furniture = _furniture.find((item: any) => item.uid = childData.ref);
  if (furniture) {

  } else {
    console.log(childData);
  }
};

const renderChild = (childData: any, types: string[]) => {
  const meshData = _mesh.find((item: any) => item.uid === childData.ref);
  if (meshData) {
    if (types.includes(meshData.type)) {
      // const vertices = new Float32Array(meshData.xyz);
      // const attrs = new THREE.BufferAttribute( vertices, 3 );

      const attrs = new THREE.Float32BufferAttribute( meshData.xyz, 3 );
      const polygonGeometry = new THREE.BufferGeometry();
      polygonGeometry.setAttribute('position', attrs);
      

      // const uvs = new Float32Array(meshData.uv);
      const uvAttribute = new THREE.Float32BufferAttribute(meshData.uv, 2);
      polygonGeometry.setAttribute('uv', uvAttribute);

      // 设置法线
      const normalAttribute = new THREE.Float32BufferAttribute(meshData.normal, 3);
      // console.log(normalAttribute);
      polygonGeometry.setAttribute('normal', normalAttribute);
      // polygonGeometry.computeVertexNormals();
      console.log(polygonGeometry.getAttribute('normal'));

      // // 设置顶点
      polygonGeometry.setIndex(meshData.faces);
      // console.log(polygonGeometry.getAttribute("uv"))

      const materialItem: any = _materialMap[meshData.material];
      let material;
      if (materialItem.colorMode === "color") {
        material = new THREE.MeshBasicMaterial({ color: new THREE.Color(materialItem.color[0], materialItem.color[1], materialItem.color[2]) });
      } else {
        // const texture = new THREE.TextureLoader().load("https://jr-prod-pim-products.oss-cn-beijing.aliyuncs.com/i/9437af46-1820-432b-b882-a1455d4d1be9/wallfloor.jpg");
        const texture = new THREE.TextureLoader().load(materialItem.texture);
        // material = new THREE.MeshStandardMaterial();
        // material.normalMap = texture;

        // // 创建UV变换矩阵
        // const matrix = new THREE.Matrix3();
        // var trans = materialItem.normalUVTransform;
        // matrix.set(trans[0], trans[1], trans[2], trans[3], trans[4], trans[5], trans[6], trans[7], trans[8]);

        // // 设置材质的normalUVTransform属性
        // texture.matrix = matrix;
        material = new THREE.MeshStandardMaterial({ map: texture });
      }
      
      const mesh = new THREE.Mesh(polygonGeometry, material);  
      _scene.add(mesh);
    } else {
      console.log(meshData.type);
    }
  } else {
    return false;
  }

  return true;
};

const renderRoom = (roomData: any) => {
  for (const children of roomData.children) {
    const isRender = renderChild(children, ["Floor"]);
    // if (isRender) {
    //   break;
    // }
    // const isRender = renderChild(children, ["WallOuter", "WallInner", "WallBottom", "WallTop", "Front", "Back", "Window", "Door", "Floor", "Ceiling", "CustomizedStructure", "Pocket"])
    // if (!isRender) {
    //   renderFurniture(children);
    // }
    // // renderChild(children, ["Pocket"]);
  }
};

const renderScene = (sceneData: any) =>{
  renderRoom(sceneData.room[0]);
  // for (const room of sceneData.room) {
  //   renderRoom(room);
  // }
};

const initScene = (data: any) => {
  const sizes = {
    width: window.innerWidth,
    height: window.innerHeight,
  };

  _mesh = data.mesh;
  _furniture = data.furniture;
  data.material.reduce((sum: any, item: any) => {
    sum[item.uid] = item;
    return sum;
  }, _materialMap);

  // 初始化场景
  const scene = new THREE.Scene();

  _scene = scene;
  const renderer = new THREE.WebGLRenderer({ canvas: _canvas });
  renderer.setSize(sizes.width, sizes.height);

  renderScene(data.scene);

  const gridHelper = new THREE.GridHelper(7, 17, 'rgb(193,193,193)', 'rgb(193,193,193)'); // 7 网格大小 17网格数量 rgb(193,193,193) 网格颜色
  gridHelper.position.set(0, -.59, -.1); //设置网格颜色
  gridHelper.visible = true; // 设置网格显示和隐藏
  scene.add(gridHelper);
  // 坐标轴辅助线
  const axesHelper = new THREE.AxesHelper(2);
  axesHelper.visible = false;
  scene.add(axesHelper);

  // 初始化相机
  camera = new THREE.PerspectiveCamera(
    65,
    sizes.width / sizes.height,
    0.01,
    20000,
  );

  camera.position.z = 10;
  camera.position.y = 5;
  camera.position.x = 1;
  // camera.zoom = 110;

  initControls(camera, renderer.domElement);

  scene.add(camera);

  // 灯光
  // const ambientLight = new THREE.AmbientLight(0x404040);
  // scene.add(ambientLight);

  var directionalLight = new THREE.DirectionalLight(0xffffff, 1);
  directionalLight.position.set(0, 1, 0);
  directionalLight.castShadow = true;
  scene.add(directionalLight);

  // 动画
  const tick = () => {
    // 更新渲染器
    renderer.render(scene, camera);
    // 页面重绘时调用自身
    window.requestAnimationFrame(tick);
  };
  tick();
};

const queryData = () => {
  fetch("https://jr-prod-cms-assets.oss-cn-beijing.aliyuncs.com/Asset/1663860a-1257-4f45-9184-e5836954ae1a/v1705051135/scene.json")
    .then(res => res.json())
    .then(data => initScene(data));
};

const Index = () => {
  const containerRef = useRef(null);
  useEffect(() => {
    _canvas = containerRef.current;
    queryData();
    // initScene(containerRef.current);
  }, []);

  const handlerTest = () => {
    console.log(camera.position);
  }

  return (
    <div className={styles.container}>
      <canvas className={styles.canvas} ref={containerRef} />
      <div className={styles.operation_container}>
        <div className={styles.operation_btn} onClick={handlerTest}>test</div>
      </div>
    </div>
  );
};

export default Index;
